<?php namespace App\Http\Controllers;

use App\Handler\Dics;
use App\Models\Dic;
use App\Http\C5\C5ResponseFactory;
use App\Models\Province;
use Illuminate\Support\Facades\DB;

class DicController extends BaseController
{

    public function all()
    {
        return C5ResponseFactory::newSuccessInstance(Dics::all());
    }

    public function grid()
    {
        $sql = "
            /* mysql comments */
            select a.* from dic a
            where 1=1
        ";
        $sql .= $this->getQueryLimits();
        $sql .= $this->getOrderBy(["dic_name" => "desc"]);
        $result = $this->gridQuery($sql);
        return C5ResponseFactory::newSuccessInstance($result);
    }

    public function edit()
    {
        $id = $this->get("dic_name");
        if (empty($id)) {
            return $this->create();
        } else {
            return $this->update();
        }
    }

    public function create()
    {
        $bean = new Dic();
        $bean->forceFill($this->request->all());
        $this->markCreateInfo($bean);
        $bean->save();

        return C5ResponseFactory::newSuccessInstance($bean);
    }

    public function detail()
    {
        $id = $this->get("dic_name");
        return $this->find($id);
    }

    public function find($dic_name)
    {
        $sql = "/**/
            select a.* from dic a where dic_name=?
        ";
        $result = DB::select($sql, [$dic_name]);
        if (empty($result)) {
            return C5ResponseFactory::newRecordNotExistsInstance();
        }
        return C5ResponseFactory::newSuccessInstance($result[0]);
    }

    public function update()
    {
        /**
         * @var  $bean Dic
         */
        $dic_name = $this->get("dic_name");
        $bean = Dic::find($dic_name);

        if (empty($bean)) {
            return C5ResponseFactory::newRecordNotExistsInstance();
        }
        $args = $this->request->all();
        $bean->forceFill($args);
        $this->markUpdateInfo($bean);

        $bean->update();
        return C5ResponseFactory::newSuccessInstance($bean);
    }

    public function delete()
    {
        /**
         * @var  $bean Dic
         */
        $dic_name = $this->get("dic_name");
        // 检查数据完整
        // $sql = "select 2 from table where dic_name=? limit 1";
        // $list = DB::select($sql,[$dic_name]);
        // if (!empty($list)) {
        //      return C5ResponseFactory::newRecordUsedInstance();
        // }

        $bean = Dic::find($dic_name);
        if (empty($bean)) {
            return C5ResponseFactory::newSuccessInstance($dic_name);
        }
        $bean->delete();
        return C5ResponseFactory::newSuccessInstance($dic_name);
    }


}

